<?php

namespace app\admin\model\service;

use app\admin\model\facrm\Customer;
use app\admin\model\facrm\Record;
use think\Exception;
use think\Model;
use traits\model\SoftDelete;

class Log extends Model
{
	use SoftDelete;

    

    

    // 表名
    protected $name = 'service_log';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $deleteTime = 'delete_time';

    // 追加属性
    protected $append = [
        'service_time_text',
        'create_time_text',
        'update_time_text',
        'delete_time_text',
		'service_client_text'
    ];
    
	static function init(){
		self::beforeWrite(function ($row) {
			$row->content_text = request()->input(['content_text'=>$row->content],'content_text',null,'trim,strip_tags,htmlspecialchars_decode');
			$row->secret_text = request()->input(['secret_text'=>$row->secret],'secret_text',null,'trim,strip_tags,htmlspecialchars_decode');
		});

		self::afterInsert(function ($row) {
			self::startTrans();
			try{
				// 自动同步到客户跟进记录
				$facrmRecordModel = new Record();
				$record_data = [
					'types' => 'customer',
					'types_id' => $row->customer_id,
					'content' => $row->content,
					'content_text' => $row->content_text,
					'record_type' => 0,
					'service_time' => $row->service_time,
					'service_hours' => $row->service_hours,
					'service_client' => $row->service_client,
					'next_time' => 0,
					'create_user_id' => $row->create_user_id,
					'from_id' => $row->id,
					'project_id' => $row->project_id,
				];
				$facrmRecordModel->save($record_data);

				// 更新客户信息
				$customerModel = new Customer();
				$customer = $customerModel->find($row->customer_id);
				$customer->follow_time = $row->service_time;
				$customer->save();

				self::commit();
			}catch (Exception $e){
				self::rollback();
			}
        });

		self::afterUpdate(function ($row) {
			// 自动同步到客户跟进记录
			$facrmRecordModel = new Record();
			$record = $facrmRecordModel->where(['from_id'=>$row->id])->find();
			if($record){
				$record->types_id = $row->customer_id;
				$record->content = $row->content;
				$record->content_text = $row->content_text;
				$record->service_time = $row->service_time;
				$record->service_hours = $row->service_hours;
				$record->service_client = $row->service_client;
				$record->create_user_id = $row->create_user_id;
				$record->from_id = $row->id;
				$record->save();
			}
		});

		self::afterDelete(function ($row) {
			$facrmRecordModel = new Record();
			$record = $facrmRecordModel->where(['from_id'=>$row->id])->find();
			$record->delete();
		});
	}
    



    public function getServiceTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['service_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getCreateTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['create_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getUpdateTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['update_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getDeleteTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['delete_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setServiceTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setCreateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setUpdateTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

    protected function setDeleteTimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }

	protected function getServiceClientTextAttr($value, $data){
		$value = $value ? $value : (isset($data['service_client']) ? $data['service_client'] : '');

		$client_data = [];
		if($value!=''){
			$clients = get_addon_config('facrm')['service_client'];
			$client_arr = explode(',', $value);
			foreach ($client_arr as $k => $v) {
				$client_data[] = isset($clients[$v]) ? $clients[$v] : '';
			}
		}
        return implode(',', $client_data);
	}


    public function customer()
    {
        return $this->belongsTo('app\admin\model\facrm\Customer', 'customer_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function project()
    {
        return $this->belongsTo('app\admin\model\workteam\Project', 'project_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function task()
    {
        return $this->belongsTo('app\admin\model\workteam\Task', 'task_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }


    public function admin()
    {
        return $this->belongsTo('app\admin\model\Admin', 'create_user_id', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
